package com.bilibili.dubbo.async;

import cn.hutool.core.collection.CollectionUtil;
import com.bilibili.model.mongo.Friend;
import com.bilibili.model.mongo.MovementTimeLine;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * @author HuangRongFu
 * 2021/11/21 星期日7:32 下午
 */

@Component
public class TimeLineService {

    @Autowired
    private MongoTemplate mongoTemplate;

    @Async
    public void saveTimeLine(Long userId, ObjectId movementId,Long currentTimeMillis){

        Query friendQuery = new Query(Criteria.where("userId").is(userId));

        List<Friend> friendList = mongoTemplate.find(friendQuery, Friend.class);

        //判断好友集合是否为空 不为空就取出好友id集合
        //在好友列表人数不多是 可以一个一个取后添加 数据量大时 采用异步处理 或者批量添加
        if (CollectionUtil.isNotEmpty(friendList)){

            //添加到时间线表中
            for (Friend friend : friendList) {

                MovementTimeLine timeLine = new MovementTimeLine();
                timeLine.setFriendId(friend.getFriendId());
                timeLine.setUserId(userId);
                timeLine.setCreated(currentTimeMillis);
                timeLine.setMovementId(movementId);//设置动态id

                mongoTemplate.insert(timeLine);
            }
        }
    }
}
